import { getMenu } from '@/api/login';
import { constantRouterMap, asyncRouterMap, defaultRouterMap, errorRouterMap } from '@/router';
import store from '../index';

/**
 * 将getMenu方法返回的menus进行整合，返回符合用户角色权限的路由表
 * @param routerMap
 * @param menus
 */
function filterAsyncRouter(routerMap, menu) {
  const accessedRouters = routerMap.filter(route => {
    if (route.hidden || route.id === -1) {
      return true;
    } else {
      for (const i in menu) {
        if (route.id === menu[i].id) {
          route.sort = menu[i].sort;
          if (menu[i]['showMode'] === 1){
            route.hidden = true;
            route.showMode = 'PLUGIN';
          }
          if (route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, menu[i].child);
          }
          return true;
        } else if (route.id === 0) { // 0代表新页面,不显示
          return false;
        }
      }
      return false;
    }
  })
  return accessedRouters;
}

/**
 * 将单独插件系统的路由做处理
 * @param route 要格式化的路由
 * @param layout 路由外层
 */
function formatPluginRouter(route, layout) {
  const pluginRouter = [];
  for (let i = 0; i < route.length; i++) {
      const formatLayout = {
        path: layout.path,
        component: layout.component,
        name: layout.name + i,
        meta: layout.meta,
        hidden: route[i].hidden || false,
        redirect: layout.redirect || (layout.path + '/' + route[i].children[0]['path']),
        showMode: 1
      };
      formatLayout.children = [route[i]];
      pluginRouter.push(formatLayout);
  }
  return pluginRouter;
}

/**
 * 将路由进行排序
 */
function sortRouter(route) {
  let router = [];

  function sortBy(props) {
    return function (a, b) {
      return b[props] - a[props];
    }
  }
  router = route.sort(sortBy('sort'));
  return router;
}

const permission = {
  state: {
    addRouters: [],
    permissionId: [],
    sidebar: [],
    sidebarLogo: {
      status: false,
      title: '',
      path: '/',
      logo: '',
      icon: ''
    }
  },
  mutations: {
    // 保存路由
    SET_ROUTERS: (state, router) => {
      const temp = sortRouter(router['accessedRouters'])
      // console.log(temp)
      state.addRouters = temp;
    },
    // 保存sidebar
    SET_SIDEBAR: (state, router) => {
      const { accessedRouters } = router;
      state.sidebar = accessedRouters;
    },
    SET_SIDEBARLOGO: (state, sidebarLogo) => {
      state.sidebarLogo = sidebarLogo;
    }
  },
  actions: {
    GetMenu({ commit, state }) {
      return new Promise((resolve, reject) => {
        getMenu().then(response => {
          const data = response.data;
          const temp = [];
          data.forEach(item => {
            temp.push(item.id);
            if (item.child && item.child.length) {
              item.child.forEach(item2 => {
                item2.id && temp.push(item2.id)
                if (item2.child && item2.child.length) {
                  item2.child.forEach(item3 => {
                    item3.id && temp.push(item3.id);
                  })
                }
              })
            }
          })
          state.permissionId = temp;

          commit('SET_ROLES', data);
          if (data && data.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data);
          } else {
            commit('SET_ROLES', [-1]);
          }
          resolve(response);
        }).catch(error => {
          reject(error);
        })
      })
    },

    /*
    * 正常模式下生成路由
    */
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menu } = data

        const url = window.location.href;
        const idx1 = url.indexOf('#/')
        const idx2 = url.substring(idx1 + 2).indexOf('/')
        const path = url.substring(idx1 + 1, idx1 + 2 + idx2)

        // 是否为插件中心模块
        let isPluginMode = false
        // 插件id
        let pluginId = null
        // 插件默认路由
        let pluginRouter = []
        for (const router of asyncRouterMap) {
          if (router.path === path) {
            pluginId = router.id
            pluginRouter = router
            break
          }
        }
        for (const m of menu) {
          if (m.id === pluginId && m.showMode) {
            isPluginMode = true
            break
          }
        }
        // console.log(path, isPluginMode, pluginId)
        let accessedRouters = defaultRouterMap;
        let tempRouters = filterAsyncRouter(asyncRouterMap, menu);
        tempRouters = tempRouters.concat(errorRouterMap);
        accessedRouters = accessedRouters.concat(tempRouters);
        commit('SET_ROUTERS', {constantRouterMap, accessedRouters});

        if (isPluginMode) {
          store.dispatch('PluginRoutes', {pluginRouter});
        } else {
          store.dispatch('DefaultRoutes', {accessedRouters});
        }
        resolve();
      })
    },

    /*
    * 正常模式下生成sidebar
    */
    DefaultRoutes({ commit }, data) {
      const { accessedRouters } = data
      commit('SET_SIDEBARLOGO', {
        status: false,
        title: '',
        path: '/',
        logo: '',
        icon: ''
      });
      commit('SET_SIDEBAR', { accessedRouters });
    },

    /*
    * 插件模式下生成sidebar
    */
    PluginRoutes({ commit }, data) {
      const { pluginRouter } = data;
      // 生成系统的路由
      const accessedRouters = [].concat(formatPluginRouter(pluginRouter['children'], pluginRouter));
      commit('SET_SIDEBARLOGO', {
        status: true,
        title: '插件中心',
        path: '/plugins/index',
        logo: '',
        icon: 'wxapp'
      });
      commit('SET_SIDEBAR', { accessedRouters })
    }
  }
}

export default permission;
